import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { ModelServiceProxy, LaunchEditDto, ComboboxItemDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { DateTimeService } from '@app/shared/common/timing/date-time.service';
import * as moment from 'moment';
@Component({
    selector: 'createOrEditLaunchModal',
    templateUrl: './create-or-edit-launch.modal.component.html'
})
export class CreateOrEditLaunchModalComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    plannedCompletionDate_Date = new Date();
    plannedFinishDate_Date = new Date();
    plannedDeliveryDate_Date = new Date();
    launch: LaunchEditDto = new LaunchEditDto();
    stages: ComboboxItemDto[] = new Array<ComboboxItemDto>();
    dtoChange: EventEmitter<any> = new EventEmitter();

    constructor(injector: Injector, private _launchService: ModelServiceProxy) {
        super(injector);
    }

    show(modelId: number, launchId?: number): void {
        this._launchService.getLaunchForEdit(launchId).subscribe(result => {
            this.launch = result.launch;
            this.launch.modelId = modelId;
            this.stages = result.stages;
            this.plannedFinishDate_Date = result.launch.plannedFinishDate.toDate();
            console.log(this.plannedFinishDate_Date);
            this.active = true;
            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;
        this.launch.plannedFinishDate = moment(this.plannedCompletionDate_Date).add('hour', 8);
        this.launch.plannedFinishDate = moment(this.plannedFinishDate_Date).add('hour', 8);
        this.launch.plannedFinishDate = moment(this.plannedDeliveryDate_Date).add('hour', 8);
        this._launchService
            .createOrUpdateLaunch(this.launch)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
